package com.bitdf.txing.search.controller;


import cn.dev33.satoken.annotation.SaCheckLogin;
import com.bitdf.txing.common.enume.TxCodeEnume;
import com.bitdf.txing.common.utils.R;
import com.bitdf.txing.common.valid.SaveGroup;
import com.bitdf.txing.search.service.GroupSaveService;
import com.bitdf.txing.search.to.GroupInfoTo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Map;
import java.util.stream.Collectors;

@RequestMapping("${txing.request.path.search}/group")
@RestController
@Slf4j
public class GroupSaveController {
    @Autowired
    GroupSaveService groupSaveService;

    /**
     * 发布组团
     * @param groupInfoTo
     * @return
     * @throws IOException
     */
    @SaCheckLogin
    @PostMapping ("/publish")
    public R productStatusUp(@Validated(SaveGroup.class) @RequestBody GroupInfoTo groupInfoTo, BindingResult result) throws IOException {
        // 判断校验是否成功
        if (result.hasErrors()) {
            Map<String, String> errors = result.getFieldErrors().stream().collect(Collectors.toMap(FieldError::getField, FieldError::getDefaultMessage));
            return R.error(TxCodeEnume.COMMON_SUBMIT_DATA_EXCEPTION).put("data", errors);
        }
        boolean b=groupSaveService.saveGroup(groupInfoTo);
        log.info("组团id:{}发布是否成功{}", groupInfoTo.getId(), b);
        return b ? R.ok() : R.error();
    }
}
